package com.laputa.web.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.actions.EventDispatchAction;

import com.laputa.service.method.BuildService;
import com.laputa.service.model.MainFrameData;

public class BuildAction extends EventDispatchAction {
	BuildService buildService;
	
	public void setBuildService(BuildService buildService) {
		this.buildService = buildService;
	}
	
	public ActionForward build(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		DynaActionForm toidentify = (DynaActionForm) form;
		String groundID = (String) toidentify.get("groundID");
		String buildingType = (String) toidentify.get("buildingType");
		MainFrameData userData = (MainFrameData) request.getSession().getAttribute("userData");
		String userID = userData.getId().toString();
		
		if ("".equals(buildingType)) {
			request.setAttribute("groundID", groundID);
			request.setAttribute("buildData", buildService.loadBuilding());
			return mapping.findForward("showBuild");
		}
		else { 
			String price = (String) toidentify.get("price");
			String message = buildService.build(buildingType, groundID, price, userID);
			request.setAttribute("message", message);
			
			MainFrameData data = buildService.apply(price, userID);
			System.out.println("from buildaction, data = " + data);
			if (data != null) 
				request.getSession().setAttribute("userData", data);
			
			request.setAttribute("showGroundData", buildService.getShowGroundData(groundID));
			request.setAttribute("resultMessage", message);
			
			return mapping.findForward("done");
		}
	}
}
